package cn.wiseda.finance.dao;

import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.List;

import org.springframework.jdbc.core.BatchPreparedStatementSetter;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.simple.ParameterizedRowMapper;
import org.springframework.jdbc.core.simple.ParameterizedSingleColumnRowMapper;
import org.springframework.stereotype.Component;

import cn.wiseda.finance.dao.util.JdbcBasicDao;
import cn.wiseda.finance.dao.util.page.Page;
import cn.wiseda.finance.dao.util.page.Pager;
import cn.wiseda.finance.dao.util.page.PaginationHelper;
import cn.wiseda.finance.entity.CashFlow;
import cn.wiseda.finance.entity.CashFlowByBank;
import cn.wiseda.finance.shiro.User;

@Component
public class CashFlowDao extends JdbcBasicDao {

	public boolean writerCashFlow(final CashFlow cf) {
		final String sql = "INSERT INTO t_cash_flow (bank_id,in_date,summary,debit,creditor,remarks,status) VALUES(?,?,?,?,?,?,0)";
		int insert = update(sql, cf.getBankId(), cf.getInDate(), cf.getSummary(), cf.getDebit(), cf.getCreditor(),
				cf.getRemarks());
		return insert > 0 ? true : false;
	}

	public List<CashFlow> getCashFlow() {
		final String sql = "SELECT * FROM t_cash_flow order by in_date";
		List<CashFlow> list = queryForBeans(sql, CashFlow.class);
		return list;
	}

	public List<CashFlowByBank> listCashFlowByBanks() {
		final String sql = "SELECT a.id as id,b.bank_name as bank_name,b.bank_code as bank_code,a.bank_id as bank_id,a.in_date as in_date,"
				+ "a.summary as summary,a.debit as debit,a.creditor as creditor,a.remarks as remarks FROM t_cash_flow a,t_bank b "
				+ "WHERE a.bank_id=b.id order by a.in_date";
		List<CashFlowByBank> list = queryForBeans(sql, CashFlowByBank.class);
		System.out.println(list.size());
		return list;
	}

	public List<CashFlow> listCashFlowByBank(int bankId) {
		final String sql = "SELECT * FROM t_cash_flow where bank_id = ? order by in_date";
		List<CashFlow> list = queryForBeans(sql, CashFlow.class, bankId);
		return list;
	}

	public Pager<CashFlow> pageCashFlowByBank(int bankId, int pageNo, int pageSize) {
		final String sql = "SELECT * FROM t_cash_flow where bank_id = ? order by in_date";
		Pager<CashFlow> page = fetchPager(sql, pageNo, pageSize, CashFlow.class, bankId);
		return page;
	}

	public void batchModifyCashFlow(final List<CashFlow> cf) {
		final String sql = "UPDATE t_cash_flow SET settle=?,STATUS='1' WHERE id=?";
		getJdbc().batchUpdate(sql, new BatchPreparedStatementSetter() {

			public void setValues(PreparedStatement ps, int index) throws SQLException {
				CashFlow cashFlow = cf.get(index);
				ps.setFloat(1, cashFlow.getSettle());
				ps.setLong(2, cashFlow.getId());
			}

			public int getBatchSize() {
				return cf.size();
			}
		});
	}
}
